package com.feiyuan.generator.controller;

import com.feiyuan.common.result.R;
import com.feiyuan.generator.pojo.dto.GeneratorCodeDTO;
import com.feiyuan.generator.service.TableListService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName TableListController
 * @Description 查询数据库中的所有表
 * @Author Xupf xupengfei131276@126.com
 * @Date 2021/9/30 9:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/generator/tableList")
//@CrossOrigin
public class TableListController {

    @Autowired
    private TableListService tableListService;

    /**
     * 查询数据库表信息
     * @return
     */
    @GetMapping("/list")
    public R list(@RequestParam("tableName") String tableName) {
        return R.ok().data("lists", tableListService.listTables(tableName));
    }

    /**
     * 生成代码
     * @param generatorCode
     * @return
     */
    //@GetMapping("/generatorCode")
    public void generatorCode(@RequestParam String generatorCode, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        GeneratorCodeDTO generatorCodeDTO = objectMapper.readValue(generatorCode, GeneratorCodeDTO.class);
        byte[] data = tableListService.generatorCode(generatorCodeDTO);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");


        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 生成代码
     * @param generatorCode
     * @return
     */
    @PostMapping("/generatorCode")
    public R generatorCode1(@RequestBody GeneratorCodeDTO generatorCode) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = tableListService.generatorCode1(generatorCode);
        return R.ok().data(map);
    }
}
